package classLoader;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author
 * @date 2021年11月26日 21:57
 * @description
 */
public class WatchDog implements Runnable{

    private ConcurrentHashMap<String, Long> fileInfos;

    public WatchDog(ConcurrentHashMap<String, Long> fileInfos) {
        this.fileInfos = fileInfos;
    }

    @Override
    public void run() {
        File file = new File(MainTest.WATCH_PAC);
        File[] watchFiles = file.listFiles();

        for (File watchFile : watchFiles) {
            long newTime = watchFile.lastModified();
            long oldTime = fileInfos.get(watchFile.getName());
            if (newTime != oldTime) {
                System.out.println("重载class文件");

                fileInfos.put(watchFile.getName(), newTime);
                loadMyClass();
            }


        }


    }


    public void loadMyClass(){
        try {
            CustomClassLoader customClassLoader = new CustomClassLoader();
            Class<?> aClass = customClassLoader.loadClass("classLoader.TestModify", false);
            Object o = aClass.newInstance();
            aClass.getMethod("test").invoke(o);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
